package org.jeecg.modules.fund.job;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.jeecg.modules.fund.entity.StockIndex;
import org.jeecg.modules.fund.service.IStockIndexService;
import org.jeecg.modules.fund.util.GlobalIndexUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

@Slf4j
@Component
public class StockIndexJob {
    @Autowired
    private IStockIndexService stockIndexService;

    @Scheduled(cron = "0 */1 8,9,10,11,13,14,15 * * MON-FRI")
    public void execute() throws InterruptedException {
        try {
            // 获取数据
            JSONArray data = GlobalIndexUtil.getHttpData();
            // 处理数据
            if(data != null && !data.isEmpty()){
                List<StockIndex> indexList = new ArrayList<>();
                // 遍历数据
                data.forEach(item -> {
                    // 格式化
                    JSONObject object = JSONObject.parseObject(item.toString());
                    // 构造实体
                    StockIndex index = new StockIndex()
                            .setId(object.getString("代码"))
                            .setCode(object.getString("代码"))
                            .setName(object.getString("名称"))
                            .setVal(object.getBigDecimal("最新价"))
                            .setVolume(object.getBigDecimal("涨跌额"))
                            .setRate(object.getBigDecimal("涨跌幅"))
                            .setOpen(object.getBigDecimal("开盘价"))
                            .setHigh(object.getBigDecimal("最高价"))
                            .setLow(object.getBigDecimal("最低价"))
                            .setLastVal(object.getBigDecimal("昨收价"))
                            .setZf(object.getBigDecimal("振幅"))
                            .setLastDatetime(object.getDate("最新行情时间"))
                            .setLastDate(object.getDate("最新行情时间"));
                    indexList.add(index);
                });
                if(!indexList.isEmpty()){
                    stockIndexService.saveOrUpdateBatch(indexList);
                }
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}
